package com.db.chat.client.network;

import com.db.chat.logging.AbstractLogger;
import com.db.chat.logging.FileSyncLogger;
import com.db.chat.logging.LoggerException;

import java.io.*;
import java.util.Date;

/**
 * Created by Student on 25.11.2014.
 */
public class Network implements Closeable{
    private DataInputStream is;
    private DataOutputStream os;

    public Network(InputStream is, OutputStream os) throws LoggerException {
        this.is = new DataInputStream(new BufferedInputStream(is));
        this.os = new DataOutputStream(new BufferedOutputStream(os));

        Thread serverChecker = new Thread(new CheckServerAlive(new FileSyncLogger("connectionLog")));
        serverChecker.start();
    }

    public void send(String str) throws com.db.chat.client.network.NetworkException {
        try {
            os.writeUTF(str);
            os.flush();
        } catch (IOException e) {
            throw new com.db.chat.client.network.NetworkException(e);
        }
    }

    public String receive() throws NetworkException {
        try {
            return is.readUTF();
        } catch (IOException e) {
            throw new NetworkException(e);
        }
    }

    @Override
    public void close() throws NetworkException {
        try {
            os.close();
            is.close();
        } catch (IOException e) {
            throw new NetworkException(e);
        }
    }

    public class CheckServerAlive implements  Runnable {
        private AbstractLogger logger;

        public CheckServerAlive(AbstractLogger logger) {
            this.logger = logger;
        }

        @Override
        public void run() {
            while (true) {
                try {
                    send("isAlive");
                    String recv = receive();
                    System.out.println(recv);
                } catch (NetworkException e) {
                    logger.write(new Date() + " Connection lost\n");
                    System.out.println("Connection lost");
                    return;
                }

                try {
                    Thread.currentThread().sleep(10000);
                } catch (InterruptedException e) {
                    logger.write(new Date() + e.getMessage() + "\n");
                }
            }
        }
    }
}
